package com.kedacom.demo.modularity.ams;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.kedacom.demo.modularity.core.BusinessException;
import com.kedacom.demo.modularity.core.JacksonUtils;

@Service("userService")
public class UserServiceImpl implements UserService {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	protected Map<String, User> users = new LinkedHashMap<String, User>();

	public UserServiceImpl() {
		init();
	}

	protected void init() {
		users.put("1", new User(1, "1", "郭靖", "guojing@test.com", "guojing", "888888", "上海", "021"));
		users.put("2", new User(2, "2", "黄蓉", "huangrong@test.com", "huangrong", "888888", "上海", "021"));
		users.put("3", new User(3, "3", "欧阳锋", null, "ouyangfeng", "888888", new Date()));
	}

	public void create(User user) {
		Assert.notNull(user);
		Assert.hasText(user.getMoid());
		Assert.hasText(user.getEmail());
		Assert.hasText(user.getUsername());

		users.put(user.getMoid(), user);
		logger.debug("create user {} success.", user);
	}

	public void update(User user) {
		Assert.notNull(user);
		Assert.hasText(user.getMoid());
		Assert.hasText(user.getEmail());
		Assert.hasText(user.getUsername());

		User oldUser = users.get(user.getMoid());
		if (oldUser == null) {
			Assert.notNull(oldUser, "用户不存在！");
		}

		users.put(user.getMoid(), user);
		logger.debug("update user {} success.", user);
	}

	public User getByMoid(String moid) throws BusinessException {
		Assert.hasText(moid);
		User user = users.get(moid);
		logger.debug("get user {} by moid {}.", user, moid);

		if (user == null) {
			throw new BusinessException("Moid不存在");
		}
		return user;
	}

	public User getByEmail(String email) {
		Assert.hasText(email);
		for (User user : users.values()) {
			if (email.equals(user.getEmail())) {
				logger.debug("get user {} by email {}.", user, email);
				return user;
			}
		}
		logger.debug("get user {} by email {}.", null, email);
		return null;
	}

	public User getByUsername(String username) throws UsernameDoseNotExistException {
		Assert.hasText(username);
		for (User user : users.values()) {
			if (username.equals(user.getUsername())) {
				logger.debug("get user {} by username {}.", user, username);
				return user;
			}
		}
		logger.debug("get user {} by username {}.", null, username);
		throw new UsernameDoseNotExistException();
	}

	public List<User> listAll() {
		logger.debug("list all users.");
		logger.debug(JacksonUtils.toJsonString(users.values()));
		return new ArrayList<User>(users.values());
	}

	public void delete(String moid) {
		Assert.hasText(moid);
		User user = users.remove(moid);
		Assert.notNull(user, "用户不存在！");
		logger.debug("delete user {}.", user);
	}

}
